package com.youle.robots.gateway.config;

import com.youle.robots.gateway.api.ErrorMsg;
import com.youle.robots.gateway.api.InterceptorExcption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 全局异常处理器
 * Created by IntelliJ IDEA.
 * User: kedong
 * Date: 18-3-29
 * Time: 下午2:53
 * To change this template use File | Settings | File and Code Templates ->Includes->File Header.
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


    /**
     * 在controller里面内容执行之前，校验一些参数不匹配啊，Get post方法不对啊之类的
     *
     * @param ex
     * @param body
     * @param headers
     * @param status
     * @param request
     * @return
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
                                                             HttpStatus status, WebRequest request) {
        System.out.println(".....");
        return super.handleExceptionInternal(ex, body, headers, status, request);
    }


    /**
     * 只处理拦截器中的异常信息，其他业务异常另外处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = InterceptorExcption.class)
    public ResponseEntity<ErrorMsg> interceptorExceptionHandle(InterceptorExcption ex) {
        String msg = ex.getMsg();
        log.error(msg);

        return new ResponseEntity<>(new ErrorMsg(msg), ex.getHttpStatus());
    }
}
